<template>
  <div>
    <div v-if="status == 'start' || status == 'recording'" class="com recording" @tap="handleRecordStop">
      <i class="if icon-stop"></i>
    </div>
    <div v-else-if="status == 'uploading'" class="com uploading">
      <i class="if icon-stop"></i>
      <div class="refresh spin"><i class="if icon-refresh"></i></div>
    </div>
    <div v-else class="com" @tap="handleRecordStart">
      <i class="if icon-mico"></i>
    </div>
  </div>
</template>

<script>
import _cos from '@/utils/cos'

const MAX_DURATION = 580000
export default {
  props: {},
  data() {
    return {
      status: 'unstart',
      tempFilePath: '',
      recordSeconds: 0,
      fileSize: 0,
      duration: 0,
    }
  },
  methods: {
    handleRecordStart () {
      if (!this.it) clearInterval(this.it)
      this.init()
      if (!this.recorder) return
      this.status = 'start'
      this.$emit('start')
      this.recorder.start({
        duration: MAX_DURATION,
        sampleRate: 44100,
        numberOfChannels: 1,
        encodeBitRate: 192000,
        format: 'aac',
        frameSize: 50
      })
    },
    handleRecordStop () {
      if (!this.recorder) return
      this.recorder.stop()
    },
    init() {
      if (this.recorder) return
      this.recorder = wx.getRecorderManager()
      this.recorder.onStart(() => {
        this.status = 'recording'
      })
      this.recorder.onStop(res => {
        this.status = 'uploading'
        this.uploadFile({
          tempFilePath: res.tempFilePath,
          fileSize: res.fileSize,
          duration: res.duration
        })
      })
    },
    async uploadFile ({
      tempFilePath, fileSize, duration
    }) {
      let rs = await _cos.upload({dir: 'materials/audios', path: tempFilePath, size: fileSize, meta: {duration}})
      this.status = 'done'
      this.$emit('ok', rs)
    }
  },
  watch: {
    status(nv) {
      this.$emit('status-change', nv)
    }
  }
}
</script>

<style scoped lang="less">
@import '../assets/less/var.less';
i {
  color: @colorPrimary;
}
.com {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  text-align: center;
  background-color: white;
  box-shadow: 0 0 5px rgba(0,0,0,.2);
  margin: 0 auto;
  i {
    line-height: 80px;
    font-size: 3em;
  }
  &.recording {
    i {
      font-size: 2.6em;
    }
  }
  &.uploading {
    position: relative;
    i {
      font-size: 2.6em;
    }
    .refresh {
      background-color: rgba(255,255,255,.8);
      position: absolute;
      z-index: 10;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      border-radius: 50%;
      i {
        color: @colorGray;
      }
    }
  }
}

</style>
